<?php


class HisItemTable extends Doctrine_Table
{

static public function getLuceneIndex()
{
  ProjectConfiguration::registerZend();
 
  if (file_exists($index = self::getLuceneIndexFile()))
  {
    return Zend_Search_Lucene::open($index);
  }
 
  return Zend_Search_Lucene::create($index);
}
 
static public function getLuceneIndexFile()
{
  return sfConfig::get('sf_data_dir').'/item.'.sfConfig::get('sf_environment').'.index';
}

  public function retrieveBackendItemList(Doctrine_Query $q)
  {
    $rootAlias = $q->getRootAlias();
    $q->leftJoin($rootAlias . '.HisCategory c');
    return $q;
  } 
  public function getAllItems(Doctrine_Query $q = null)
  {
    return $this->addAllItemsQuery($q)->execute();
  }
 
  public function countAllItems(Doctrine_Query $q = null)
  {
    return $this->addAllItemsQuery($q)->count();
  }
 
  public function addAllItemsQuery(Doctrine_Query $q = null)
  {
    if (is_null($q))
    {
      $q = Doctrine_Query::create()
        ->from('HisItem j');
    }
 
    $alias = $q->getRootAlias();
 
    $q->addOrderBy($alias . '.brand DESC');
 
    return $q;
  }
 
	 public function save(Doctrine_Connection $conn = null)
	{
  $conn = $conn ? $conn : $this->getTable()->getConnection();
  $conn->beginTransaction();
  try
  {
    $ret = parent::save($conn);
 
    $this->updateLuceneIndex();
 
    $conn->commit();
 
    return $ret;
  }
  catch (Exception $e)
  {
    $conn->rollBack();
    throw $e;
  }
  
  }
  
  
  public function getForLuceneQuery($query)
{
  $hits = self::getLuceneIndex()->find($query);
 
  $pks = array();
  foreach ($hits as $hit)
  {
    $pks[] = $hit->pk;
  }
 
  if (empty($pks))
  {
    return array();
  }
 
  $q = $this->createQuery('j')
    ->whereIn('j.id', $pks)
    ->limit(20);
 
  $q = $this->addAllItemsQuery($q);
 
  return $q->execute();
}
  }